<template>
  <div class="gantt-chart-container">
    <div class="chart-header">
      <h3>{{ chartTitle }}</h3>
    </div>
    <div class="chart-wrapper">
      <div ref="ganttChart" :style="{ height: chartHeight + 'px', width: '100%' }"></div>
    </div>
    
    <!-- 工序颜色说明和统计信息 -->
    <div v-if="operationColorMap.size > 0" class="chart-footer">
      <div class="operation-legend">
        <h4>工序颜色说明</h4>
        <div class="legend-items">
          <div 
            v-for="[operationId, color] in operationColorMap" 
            :key="operationId" 
            class="legend-item"
          >
            <div class="color-box" :style="{ backgroundColor: color }"></div>
            <span class="operation-name">{{ operationId }}</span>
          </div>
        </div>
      </div>
      
      <div class="chart-stats">
        <h4>排产统计</h4>
        <div class="stats-row">
          <div class="stat-item">
            <span class="stat-label">机器数量:</span>
            <span class="stat-value">{{ machines.length }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">工序数量:</span>
            <span class="stat-value">{{ operationColorMap.size }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">任务数量:</span>
            <span class="stat-value">{{ seriesDataCount }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">时间跨度:</span>
            <span class="stat-value">{{ timeSpanText }}</span>
          </div>
        </div>
      </div>
    </div>
    

  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue';
import * as echarts from 'echarts';



// 定义props
const props = defineProps({
  planData: {
    type: Object,
    default: () => ({})
  },
  productionTasks: {
    type: Array,
    default: () => []
  },
  scheduleDetails: {
    type: Array,
    default: () => []
  }
});

const ganttChart = ref(null);
let chartInstance = null;



// 算法名称映射
const algorithmNameMap = {
  'PRODUCT_BATCH': '同种产品集中生产算法', 
  'MACHINE_UTILIZATION': '负载均衡算法',
  'ENHANCED_GENETIC_ALGORITHM': '增强遗传算法',
  'DEFAULT_FIFO': 'FIFO默认排序算法',
  'CRITICAL_PATH_SPT': '关键路径SPT算法',
  'COMBINE_ALGORITHM': '紧急优先与机器利用率结合算法',

};

// 工序颜色配置
const operationColors = [
  '#FF6B6B', // 红色
  '#4ECDC4', // 青色
  '#45B7D1', // 蓝色
  '#96CEB4', // 绿色
  '#FECA57', // 黄色
  '#FF9FF3', // 粉色
  '#54A0FF', // 浅蓝色
  '#5F27CD', // 紫色
  '#00D2D3', // 蓝绿色
  '#FF9F43', // 橙色
  '#6C5CE7', // 蓝紫色
  '#A3CB38', // 青绿色
  '#FDA7DF', // 浅粉色
  '#FC427B', // 深粉色
  '#26DE81', // 绿色
  '#1B9CFC', // 深蓝色
  '#B53471', // 紫红色
  '#F8B500', // 金色
  '#0ABDE3', // 天蓝色
  '#C44569'  // 深紫色
];

// 工序颜色映射
const operationColorMap = ref(new Map());

// 为工序分配颜色
const getOperationColor = (operationId) => {
  if (!operationId) return '#5470C6'; // 默认蓝色
  
  if (!operationColorMap.value.has(operationId)) {
    const colorIndex = operationColorMap.value.size % operationColors.length;
    operationColorMap.value.set(operationId, operationColors[colorIndex]);
  }
  
  return operationColorMap.value.get(operationId);
};

// 时间解析函数
const parseTime = (timeStr) => {
  if (!timeStr) return Date.now();
  
  try {
    let cleanTime = timeStr.toString().trim();
    if (cleanTime.includes(' ') && !cleanTime.includes('T')) {
      cleanTime = cleanTime.replace(' ', 'T');
    }
    
    const date = new Date(cleanTime);
    return isNaN(date.getTime()) ? Date.now() : date.getTime();
  } catch (error) {
    console.error('时间解析错误:', error);
    return Date.now();
  }
};

// 获取算法中文名称
const getAlgorithmDisplayName = (englishName) => {
  return algorithmNameMap[englishName] || englishName;
};

// 计算图表标题
const chartTitle = computed(() => {
  if (!props.planData.planName || !props.planData.algorithmType) {
    return '排产甘特图（机器编号为纵轴）';
  }
  const algorithmName = getAlgorithmDisplayName(props.planData.algorithmType);
  return `${props.planData.planName}-${algorithmName}`;
});

// 获取机器列表
const machines = computed(() => {
  const machineSet = new Set();
  
  // 从排产详情中提取机器ID
  if (props.scheduleDetails && props.scheduleDetails.length > 0) {
    props.scheduleDetails.forEach(detail => {
      if (detail.machineId) {
        machineSet.add(detail.machineId.trim());
      }
    });
  }
  
  // 从生产任务中提取机器ID
  if (props.productionTasks && props.productionTasks.length > 0) {
    props.productionTasks.forEach(task => {
      if (task.machineId) {
        machineSet.add(task.machineId.trim());
      }
    });
  }
  
  return Array.from(machineSet).sort();
});

// 计算图表高度
const chartHeight = computed(() => {
  const baseHeight = 400;
  const machineHeight = 50;
  return Math.max(baseHeight, machines.value.length * machineHeight + 100);
});

// 计算时间跨度
const timeSpanText = computed(() => {
  let minTime = Number.MAX_VALUE;
  let maxTime = Number.MIN_VALUE;
  
  // 从排产详情获取时间范围
  if (props.scheduleDetails && props.scheduleDetails.length > 0) {
    props.scheduleDetails.forEach(detail => {
      if (detail.scheduledStartTime && detail.scheduledEndTime) {
        const startTime = parseTime(detail.scheduledStartTime);
        const endTime = parseTime(detail.scheduledEndTime);
        minTime = Math.min(minTime, startTime);
        maxTime = Math.max(maxTime, endTime);
      }
    });
  } 
  // 从生产任务获取时间范围
  else if (props.productionTasks && props.productionTasks.length > 0) {
    props.productionTasks.forEach(task => {
      if (task.planStartTime && task.planEndTime) {
        const startTime = parseTime(task.planStartTime);
        const endTime = parseTime(task.planEndTime);
        minTime = Math.min(minTime, startTime);
        maxTime = Math.max(maxTime, endTime);
      }
    });
  }
  
  if (minTime === Number.MAX_VALUE || maxTime === Number.MIN_VALUE) {
    return '-';
  }
  
  const durationMs = maxTime - minTime;
  const durationHours = Math.round(durationMs / (1000 * 60 * 60));
  const durationDays = Math.round(durationHours / 24);
  
  if (durationDays > 0) {
    return `${durationDays}天${durationHours % 24}小时`;
  } else {
    return `${durationHours}小时`;
  }
});

// 获取操作相关的任务信息
const getTaskByTaskId = (taskId) => {
  return props.productionTasks?.find(task => task.taskId === taskId) || null;
};

// 生成甘特图数据
const generateGanttData = () => {
  
  const seriesData = [];
  const machineList = machines.value;
  
  if (machineList.length === 0) {
    
    return [];
  }
  
  
  
  // 清空工序颜色映射，重新分配
  operationColorMap.value.clear();
  
  // 优先使用排产详情
  if (props.scheduleDetails && props.scheduleDetails.length > 0) {
    
    
    props.scheduleDetails.forEach((detail, index) => {
      if (!detail.machineId || !detail.scheduledStartTime || !detail.scheduledEndTime) {
        
        return;
      }
      
      const machineIndex = machineList.indexOf(detail.machineId);
      if (machineIndex < 0) {
        
        return;
      }
      
      const startTime = parseTime(detail.scheduledStartTime);
      const endTime = parseTime(detail.scheduledEndTime);
      
      if (startTime >= endTime) {
        
        return;
      }
      
      // 获取关联的生产任务信息，获取工序ID
      const relatedTask = getTaskByTaskId(detail.taskId);
      const operationId = relatedTask?.operationId || `OP_${index + 1}`;
      const workOrderId = relatedTask?.workOrderId || '';
      const quantity = relatedTask?.quantity || 0;
      
      // 根据工序ID获取颜色
      const color = getOperationColor(operationId);
      
      seriesData.push({
        value: [
          machineIndex, 
          startTime, 
          endTime, 
          detail.taskId || `任务${index + 1}`, 
          detail.machineId,
          operationId,
          workOrderId,
          quantity
        ],
        itemStyle: { 
          color: color,
          borderColor: '#fff',
          borderWidth: 1
        }
      });
    });
  } 
  // 如果没有排产详情，使用生产任务
  else if (props.productionTasks && props.productionTasks.length > 0) {
    
    
    props.productionTasks.forEach((task, index) => {
      if (!task.machineId || !task.planStartTime || !task.planEndTime) {
        
        return;
      }
      
      const machineIndex = machineList.indexOf(task.machineId);
      if (machineIndex < 0) {
        
        return;
      }
      
      const startTime = parseTime(task.planStartTime);
      const endTime = parseTime(task.planEndTime);
      
      if (startTime >= endTime) {
        
        return;
      }
      
      // 根据工序ID获取颜色
      const operationId = task.operationId || `OP_${index + 1}`;
      const color = getOperationColor(operationId);
      
      seriesData.push({
        value: [
          machineIndex, 
          startTime, 
          endTime, 
          task.taskId || task.workOrderId || `任务${index + 1}`, 
          task.machineId,
          operationId,
          task.workOrderId || '',
          task.quantity || 0
        ],
        itemStyle: { 
          color: color,
          borderColor: '#fff',
          borderWidth: 1
        }
      });
    });
  }
  
  
  
  return seriesData;
};

// 简化的图表初始化
const initChart = () => {
  
  
  if (!ganttChart.value) {
    
    return false;
  }
  
  // 销毁现有实例
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  
  // 检查容器尺寸
  const rect = ganttChart.value.getBoundingClientRect();
  
  
  
  if (rect.width === 0 || rect.height === 0) {
    
    return false;
  }
  
  // 创建图表实例
  try {
    chartInstance = echarts.init(ganttChart.value);
    
  } catch (error) {
    
    return false;
  }
  
  return true;
};

// 渲染甘特图
const renderChart = () => {
  
  
  if (!chartInstance && !initChart()) {
    
    return;
  }
  
  const machineList = machines.value;
  const seriesData = generateGanttData();
  
  
  
  if (seriesData.length === 0) {
    
    chartInstance.setOption({
      title: {
        text: '暂无排产数据',
        left: 'center',
        top: 'center',
        textStyle: { fontSize: 16, color: '#999' }
      }
    });
    return;
  }
  
  // 生成工序图例
  const operationLegend = Array.from(operationColorMap.value.entries()).map(([operationId, color]) => ({
    name: operationId,
    itemStyle: { color }
  }));

  // 设置图表配置
  const option = {
    title: {
      text: chartTitle.value,
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(50,50,50,0.9)',
      borderColor: '#fff',
      borderWidth: 1,
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      formatter: function (params) {
        const start = new Date(params.value[1]).toLocaleString('zh-CN', {
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
        const end = new Date(params.value[2]).toLocaleString('zh-CN', {
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
        const duration = Math.round((params.value[2] - params.value[1]) / (1000 * 60)); // 分钟
        
        let html = `<div style="padding: 8px;">`;
        html += `<div style="font-weight: bold; margin-bottom: 6px; color: #FFD700;">📋 任务信息</div>`;
        html += `<div>任务ID：${params.value[3]}</div>`;
        if (params.value[6]) {
          html += `<div>工单ID：${params.value[6]}</div>`;
        }
        if (params.value[5]) {
          html += `<div>工序ID：<span style="color: ${params.color}; font-weight: bold;">${params.value[5]}</span></div>`;
        }
        html += `<div>机器：${params.value[4]}</div>`;
        if (params.value[7]) {
          html += `<div>数量：${params.value[7]}</div>`;
        }
        html += `<div style="margin-top: 6px; padding-top: 6px; border-top: 1px solid #666;">`;
        html += `<div>开始：${start}</div>`;
        html += `<div>结束：${end}</div>`;
        html += `<div>时长：${duration} 分钟</div>`;
        html += `</div>`;
        html += `</div>`;
        
        return html;
      }
    },
    legend: {
      type: 'scroll',
      orient: 'horizontal',
      top: 40,
      left: 'center',
      itemWidth: 14,
      itemHeight: 14,
      textStyle: {
        fontSize: 11
      },
      data: operationLegend.map(item => item.name),
      formatter: function(name) {
        return `工序: ${name}`;
      }
    },
    grid: {
      left: 100,
      right: 60,
      top: operationLegend.length > 0 ? 80 : 60,
      bottom: 80,
      containLabel: false
    },
    xAxis: {
      type: 'time',
      name: '时间轴',
      nameLocation: 'middle',
      nameGap: 35,
      nameTextStyle: {
        fontSize: 12,
        color: '#666'
      },
      axisLabel: {
        fontSize: 10,
        color: '#666',
        formatter: function(value) {
          return echarts.format.formatTime('MM-dd hh:mm', value);
        }
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      }
    },
    yAxis: {
      type: 'category',
      name: '机器设备',
      nameLocation: 'middle',
      nameGap: 60,
      nameTextStyle: {
        fontSize: 12,
        color: '#666'
      },
      data: machineList,
      axisLabel: {
        fontSize: 11,
        color: '#333',
        formatter: (value) => value
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#f5f5f5'
        }
      }
    },
    dataZoom: [
      {
        type: 'slider',
        show: true,
        xAxisIndex: [0],
        start: 0,
        end: 100,
        bottom: 15,
        height: 20,
        textStyle: {
          fontSize: 10
        }
      },
      {
        type: 'inside',
        xAxisIndex: [0],
        zoomOnMouseWheel: true,
        moveOnMouseMove: true,
        moveOnMouseWheel: false
      }
    ],
    toolbox: {
      show: true,
      right: 15,
      top: 15,
      feature: {
        dataZoom: {
          yAxisIndex: 'none',
          title: {
            zoom: '区域缩放',
            back: '还原缩放'
          }
        },
        restore: {
          title: '还原'
        },
        saveAsImage: {
          title: '保存为图片',
          pixelRatio: 2
        }
      },
      iconStyle: {
        borderColor: '#666'
      },
      emphasis: {
        iconStyle: {
          borderColor: '#409eff'
        }
      }
    },
    series: [{
      type: 'custom',
      renderItem: function (params, api) {
        try {
          const yIndex = api.value(0);
          const start = api.coord([api.value(1), yIndex]);
          const end = api.coord([api.value(2), yIndex]);
          const height = 30;
          const width = Math.max(end[0] - start[0], 3); // 最小宽度3px
          
          // 创建任务条
          const rect = {
            type: 'rect',
            shape: {
              x: start[0],
              y: start[1] - height / 2,
              width: width,
              height: height
            },
            style: {
              fill: api.visual('color'),
              stroke: '#fff',
              lineWidth: 2,
              shadowBlur: 4,
              shadowColor: 'rgba(0,0,0,0.1)',
              shadowOffsetY: 2
            }
          };
          
          // 如果任务条足够宽，添加任务持续时间文本
          const elements = [rect];
          if (width > 60) {
            // 计算任务持续时间（小时数）
            const startTime = api.value(1);
            const endTime = api.value(2);
            const durationMs = endTime - startTime;
            const durationHours = (durationMs / (1000 * 60 * 60)).toFixed(2); // 转换为小时并保留两位小数
            
            const durationText = `${durationHours}h`;
            if (durationText) {
              elements.push({
                type: 'text',
                style: {
                  text: durationText,
                  x: start[0] + width / 2,
                  y: start[1],
                  fill: '#fff',
                  fontSize: 10,
                  fontWeight: 'bold',
                  textAlign: 'center',
                  textVerticalAlign: 'middle',
                  textShadowColor: 'rgba(0,0,0,0.5)',
                  textShadowBlur: 2
                }
              });
            }
          }
          
          return {
            type: 'group',
            children: elements
          };
        } catch (error) {
          console.error('renderItem错误:', error);
          return null;
        }
      },
      encode: {
        x: [1, 2],
        y: 0
      },
      data: seriesData
    }]
  };
  
  console.log('设置图表配置');
  
  try {
    chartInstance.setOption(option, true); // 第二个参数true表示不合并配置
    console.log('图表渲染成功');
  } catch (error) {
    console.error('设置图表配置失败:', error);
  }
};

// 调试方法
const reloadChart = () => {
  console.log('手动重新加载图表');
  nextTick(() => {
    renderChart();
  });
};

const logDebugInfo = () => {
  console.log('=== 调试信息 ===');
  console.log('Props:', props);
  console.log('机器列表:', machines.value);
  console.log('生产任务:', props.productionTasks);
  console.log('排产详情:', props.scheduleDetails);
  console.log('图表实例:', chartInstance);
  console.log('容器元素:', ganttChart.value);
  if (ganttChart.value) {
    console.log('容器尺寸:', ganttChart.value.getBoundingClientRect());
  }
  console.log('===============');
};

// 监听数据变化
watch([() => props.productionTasks, () => props.scheduleDetails], () => {
  console.log('数据变化，重新渲染');
  nextTick(() => {
    renderChart();
  });
}, { deep: true });

// 组件挂载
onMounted(() => {
  console.log('组件挂载');
  nextTick(() => {
    setTimeout(() => {
      renderChart();
    }, 100);
  });
});

// 公开方法
const init = () => {
  console.log('外部调用init方法');
  nextTick(() => {
    renderChart();
  });
};

// 开启调试信息
const enableDebug = () => {
  showDebugInfo.value = true;
  console.log('甘特图调试信息已开启');
};

defineExpose({ init, reloadChart, logDebugInfo, enableDebug });
</script>

<style scoped>
.gantt-chart-container {
  width: 100%;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  overflow: hidden;
}

.chart-header {
  padding: 20px 20px 15px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-bottom: none;
}

.chart-header h3 {
  margin: 0;
  color: #fff;
  font-weight: 600;
  font-size: 18px;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.chart-wrapper {
  padding: 25px 20px 20px 20px;
  min-height: 400px;
  background: #fafafa;
}

.debug-info {
  padding: 15px;
  background: #f5f5f5;
  border-top: 1px solid #e8e8e8;
  font-size: 12px;
  color: #666;
}

.debug-info h4 {
  margin: 0 0 10px 0;
  color: #409eff;
  font-size: 14px;
}

.debug-info p {
  margin: 5px 0;
}

.debug-info button {
  margin: 5px 10px 5px 0;
  padding: 5px 10px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
}

.debug-info button:hover {
  background: #337ab7;
}

.chart-footer {
  background: #f9f9f9;
  border-top: 1px solid #e8e8e8;
  border-radius: 0 0 12px 12px;
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  padding: 20px;
}

.operation-legend {
  background: transparent;
  padding: 0;
  border: none;
  border-radius: 0;
}

.operation-legend h4 {
  margin: 0 0 12px 0;
  color: #409eff;
  font-size: 14px;
  font-weight: 600;
}

.legend-items {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.legend-item {
  display: flex;
  align-items: center;
  background: white;
  padding: 6px 12px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.legend-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.color-box {
  width: 16px;
  height: 16px;
  border-radius: 3px;
  margin-right: 8px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.operation-name {
  font-size: 12px;
  color: #333;
  font-weight: 500;
  white-space: nowrap;
}

.chart-stats h4 {
  margin: 0 0 12px 0;
  color: #409eff;
  font-size: 14px;
  font-weight: 600;
}

.stats-row {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 8px 12px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.stat-label {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.stat-value {
  font-size: 14px;
  color: #333;
  font-weight: 600;
}

@media (max-width: 768px) {
  .chart-footer {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .legend-items {
    gap: 10px;
  }
  
  .legend-item {
    padding: 4px 8px;
  }
}
</style> 